package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {

    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ApArticleMapper apArticleMapper;

    /**
     * 生成静态文件上传到minIO中
     *
     * @param apArticle
     * @param content
     */
    @Async
    @Override
    public void buildArticleToMinIO(ApArticle apArticle, String content) {

        try {
            Map dataModel = new HashMap();
            // 将文章内容转换成集合
            JSONArray objects = JSONArray.parseArray(content);
            dataModel.put("content", objects);

            // 2.获取模板
            Template template = configuration.getTemplate("article.ftl");

            // 3.合成静态文件
            Writer out = new StringWriter();
            template.process(dataModel, out);

            // 4.将文件上传到minio中
            InputStream is = new ByteArrayInputStream(out.toString().getBytes(StandardCharsets.UTF_8));
            String url = fileStorageService.uploadHtmlFile("", apArticle.getId() + ".html", is);

            // 5.修改article的字段
            apArticle = apArticleMapper.selectById(apArticle.getId());
            apArticle.setStaticUrl(url);

            apArticleMapper.updateById(apArticle);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
